package com.aw.baselib.util

import android.content.Context
import com.aw.baselib.base.AwBaseApplication

/**
 * Created by hzw
 */
object SPUtils {
    var instance: SPUtils? = null
        get() {
            if (field == null) {
                field = SPUtils
            }
            return field
        }
        private set

    /**
     * 保存在手机里面的文件名
     */
    const val FILE_NAME = "share_data"

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param object
     */
    @JvmStatic
    fun put(key: String?, `object`: Any) {
        val sp =
            AwBaseApplication.instance?.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editor = sp?.edit()
        if (`object` is String) {
            editor?.putString(key, `object`)
        } else if (`object` is Int) {
            editor?.putInt(key, `object`)
        } else if (`object` is Boolean) {
            editor?.putBoolean(key, `object`)
        } else if (`object` is Float) {
            editor?.putFloat(key, `object`)
        } else if (`object` is Long) {
            editor?.putLong(key, `object`)
        } else {
            editor?.putString(key, `object`.toString())
        }
        editor?.commit()
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param key
     * @param defaultObject
     * @return
     */
    @JvmStatic
    operator fun get(key: String?, defaultObject: Any?): Any? {
        val sp =
            AwBaseApplication.instance?.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        if (defaultObject is String) {
            return sp?.getString(key, defaultObject as String?)
        } else if (defaultObject is Int) {
            return sp?.getInt(key, (defaultObject as Int?)!!)
        } else if (defaultObject is Boolean) {
            return sp?.getBoolean(key, (defaultObject as Boolean?)!!)
        } else if (defaultObject is Float) {
            return sp?.getFloat(key, (defaultObject as Float?)!!)
        } else if (defaultObject is Long) {
            return sp?.getLong(key, (defaultObject as Long?)!!)
        }
        return null
    }
}